//
//  UIView+A.swift
//  Pods
//
//  Created by 100Years on 2025/3/6.
//

import UIKit

public extension UIView {
    // MARK: - 旋转动画控制
    /// 开始旋转动画
    /// - Parameters:
    ///   - duration: 单圈旋转时间（默认 1 秒）
    ///   - clockwise: 是否顺时针旋转（默认 true）
    ///   - repeatCount: 重复次数（默认无限循环 .greatestFiniteMagnitude）
    func startRotating(duration: CFTimeInterval = 1.0,
                     clockwise: Bool = true,
                     repeatCount: Float = .greatestFiniteMagnitude) {
        // 同步移除已有旋转动画
        self.stopRotating()
        
        DispatchQueue.main.async {
            // 创建旋转动画
            let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
            rotationAnimation.fromValue = 0
            rotationAnimation.toValue = clockwise ? CGFloat.pi * 2.0 : -CGFloat.pi * 2.0
            rotationAnimation.duration = duration
            rotationAnimation.isCumulative = true
            rotationAnimation.repeatCount = repeatCount
            rotationAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
            
            // 防止动画结束后恢复初始状态
            rotationAnimation.fillMode = .forwards
            rotationAnimation.isRemovedOnCompletion = false
            
            // 添加动画到视图的 layer
            self.layer.add(rotationAnimation, forKey: "rotationAnimation")
        }
    }
    
    /// 停止旋转动画
    func stopRotating() {
        // 同步移除旋转动画
        DispatchQueue.main.async {
            self.layer.removeAnimation(forKey: "rotationAnimation")
        }
    }
}

public extension UIView {
    /// 图片透明度循环动画
    /// - Parameters:
    ///   - minAlpha: 最小透明度（默认为 0.1）
    ///   - duration: 动画时长（单次透明度变化的时长，默认为 1 秒）
    func startAlphaAnimation(minAlpha: CGFloat = 0.1, duration: TimeInterval = 1.0) {
        // 防止重复添加动画
        self.layer.removeAllAnimations()
        
        // 开始动画
        UIView.animate(withDuration: duration, delay: 0, options: [.autoreverse, .repeat]) {
            self.alpha = minAlpha
        } completion: { _ in
            self.alpha = 1.0 // 确保最终状态为 1.0
        }
    }
    
    /// 停止透明度动画
    func stopAlphaAnimation() {
        self.layer.removeAllAnimations()
        self.alpha = 1.0 // 恢复到默认状态
    }
}

public extension UIView {
    /// 设置绝对旋转角度
    ///   - angle: 旋转角度（度数）
    func setRotation(angle: CGFloat) {
        let radians = angle * .pi / 180
        self.transform = CGAffineTransform(rotationAngle: radians)
    }
}
